import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'dart:async';

import 'package:signage/app/utils/http_client.dart';
import 'package:signage/app/utils/toast_utils.dart';
import 'package:signage/l10n/l10n.dart';

class PhoneEditDialog extends StatelessWidget {
  final TextEditingController phoneController;
  final TextEditingController codeController;
  final VoidCallback? onConfirm;
  final VoidCallback? onCancel;
  final VoidCallback? onGetCode;

  const PhoneEditDialog({
    Key? key,
    required this.phoneController,
    required this.codeController,
    this.onConfirm,
    this.onCancel,
    this.onGetCode,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Dialog(
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(16.r),
      ),
      child: Container(
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(16.r),
        ),
        width: 280.w,
        padding: EdgeInsets.all(20.w),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text(
              AppLocalizations.of(context)!.translate('change_phone_number'),
              style: TextStyle(
                fontSize: 16.sp,
                color: Color(0xFF333333),
              ),
            ),
            SizedBox(height: 20.h),
            // 手机号输入框
            TextField(
              controller: phoneController,
              keyboardType: TextInputType.phone,
              decoration: InputDecoration(
                fillColor: Color(0xFFF7F7F7),
                filled: true,
                hintText: AppLocalizations.of(context)!.translate('enter_phone'),
                hintStyle: TextStyle(
                  color: Colors.black38,
                  fontSize: 14.sp,
                ),
                border: InputBorder.none,
                enabledBorder: InputBorder.none,
                focusedBorder: InputBorder.none,
                contentPadding: EdgeInsets.symmetric(
                  horizontal: 12.w,
                  vertical: 8.h,
                ),
              ),
            ),
            SizedBox(height: 12.h),
            // 验证码输入框和获取验证码按钮
            Row(
              children: [
                Expanded(
                  child: TextField(
                    controller: codeController,
                    keyboardType: TextInputType.number,
                    decoration: InputDecoration(
                      fillColor: Color(0xFFF7F7F7),
                      filled: true,
                      hintText: AppLocalizations.of(context)!.translate('enter_verification_code'),
                      hintStyle: TextStyle(
                        color: Colors.black38,
                        fontSize: 14.sp,
                      ),
                      border: InputBorder.none,
                      enabledBorder: InputBorder.none,
                      focusedBorder: InputBorder.none,
                      contentPadding: EdgeInsets.symmetric(
                        horizontal: 12.w,
                        vertical: 8.h,
                      ),
                    ),
                  ),
                ),
                SizedBox(width: 12.w),
                _CountDownButton(
                    phoneController: phoneController, onGetCode: onGetCode),
              ],
            ),
            SizedBox(height: 20.h),
            // 按钮组
            Row(
              children: [
                Expanded(
                  child: InkWell(
                    onTap: onCancel ?? () => Get.back(),
                    child: Container(
                      alignment: Alignment.center,
                      padding:
                          EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
                      decoration: BoxDecoration(
                        color: Color(0xFFEFEFEF),
                        borderRadius: BorderRadius.circular(28.r),
                      ),
                      child: Text(
                        AppLocalizations.of(context)!.translate('cancel'),
                        style: TextStyle(
                          fontSize: 14.sp,
                          color: Color(0xFF333333),
                        ),
                      ),
                    ),
                  ),
                ),
                SizedBox(width: 12.w),
                Expanded(
                  child: InkWell(
                    onTap: onConfirm,
                    child: Container(
                      alignment: Alignment.center,
                      padding:
                          EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
                      decoration: BoxDecoration(
                        color: Color(0xFFFCCF01),
                        borderRadius: BorderRadius.circular(28.r),
                      ),
                      child: Text(
                        AppLocalizations.of(context)!.translate('confirm'),
                        style: TextStyle(
                          fontSize: 14.sp,
                          color: Color(0xFF333333),
                        ),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}

// 添加倒计时按钮组件
class _CountDownButton extends StatefulWidget {
  final TextEditingController phoneController;
  final VoidCallback? onGetCode;

  const _CountDownButton({
    Key? key,
    required this.phoneController,
    this.onGetCode,
  }) : super(key: key);

  @override
  State<_CountDownButton> createState() => _CountDownButtonState();
}

class _CountDownButtonState extends State<_CountDownButton> {
  Timer? _timer;
  int _countDown = 0;

  @override
  void dispose() {
    _timer?.cancel();
    super.dispose();
  }

  void _startCountDown() {
    setState(() {
      _countDown = 60;
    });

    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (_countDown == 0) {
        timer.cancel();
        return;
      }
      setState(() {
        _countDown--;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: _countDown > 0
          ? null
          : () async {
              if (widget.phoneController.text.isEmpty) {
                ToastUtils.show(AppLocalizations.of(context)!.translate('enter_phone'));
                return;
              }
              final httpClient = HttpClient();
              try {
                final response = await httpClient.getCaptcha2(
                    mobile: widget.phoneController.text);
                ToastUtils.show(AppLocalizations.of(context)!.translate('verification_code_sent'));
                widget.onGetCode?.call();
                _startCountDown();
              } catch (e) {}
            },
      child: Text(
        _countDown > 0
            ? AppLocalizations.of(context)!.translate('retry_after_seconds').replaceAll('{seconds}', _countDown.toString())
            : AppLocalizations.of(context)!.translate('get_verification_code'),
        style: TextStyle(
          fontSize: 14.sp,
          color: _countDown > 0 ? Colors.grey : Color(0xFF333333),
        ),
      ),
    );
  }
}
